from lib import get_fields

class GobyFormat:
    def __init__(self):
        self.favicons = []
    @property
    def __assets_fields(self):
        return [
            'ip',
            'mac',
            'os',
            'hostname',
            'honeypot',
            'product'
        ]
    def assets_format(self, assets) -> list:
        """将assets信息进行整理, 返回一个列表对象 """
        results = []
        for ip in assets['ips']:
            result = {}
            for field in self.__assets_fields:
                result[field] = get_fields(ip, field)
            if ip['vulnerabilities']:
                result['vulnerabilities'] = len(ip['vulnerabilities'])
            else:
                result['vulnerabilities'] = 0
            result['ports'], result['protocols'] = self.protocols_format(ip['protocols'])
            result.update(self.tags_format(ip['tags']))
            results.append(result)
        return results
    
    def protocols_format(self, protocols: dict):
        ports = []
        results = [] # 存放协议信息
        if not protocols:
            return ('', '')
        
        for value in protocols.values():
            ports.append(value['port'])
            results.append(value['protocol'])
        
        return (','.join(ports), ','.join(results))    
        
        
    def tags_format(self, tags:list):
        """格式化tag信息内容
        
        @args: 
            tags: 存储tag信息的列表,其中1,2,3,4,5分别代表硬件层,系统层,服务层,支撑层,应用层
        
        """
        application_layers = []
        support_layers = []
        service_layers = []
        system_layers = []
        hardware_layers = []
        layers = [hardware_layers, system_layers, service_layers, support_layers, application_layers]
        if not tags:
            return {'hardware_layers': '',
                    'system_layers': '',
                    'service_layers': '',
                    'support_layers': '',
                    'application_layers': '' 
                    }
        for tag in tags:
            layer_num = int(tag['level']) - 1
            layers[layer_num].append(tag['product'])
        
        return {
            'hardware_layers': ','.join(layers[0]),
            'system_layers': ','.join(layers[1]),
            'service_layers': ','.join(layers[2]),
            'support_layers': ','.join(layers[3]),
            'application_layers': ','.join(layers[4]),
        }
            
